package com.show.service.eact;


import com.show.dto.Event;
import com.show.dto.activiti.DeploymentBean;
import com.show.dto.activiti.ProcessDefinitionBean;
import com.show.dto.activiti.TaskBean;
import com.show.dto.activiti.WorkFlow;
import com.show.service.draw_time.DrawTimeService;
import com.show.util.UploadUtil;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作流微服务
 *
 * @author 王玉涛
 * @Param
 * @date 2017-09-28 13:48
 */
@Service
public class EactServer {

    @Autowired
    private EasyActService easyActService;
    @Autowired
    private DrawTimeService drawTimeService;

    public List<DeploymentBean> deployHome() {
        List<DeploymentBean> depList = easyActService.findDeploymentList();
        return depList;
    }

    public List<ProcessDefinitionBean> processHome(Integer page, Integer pageSize) {
        List<ProcessDefinitionBean> pdList = easyActService.findProcessDefinitionList(page, pageSize);
        return pdList;
    }


    public String newdeploy(MultipartFile file, @RequestParam("filename") String filename) {

        // 获取页面传递的值
        // 1：获取页面上传递的zip格式的文件，格式是MultipartFile类型
        // 2：调用上传文件方法，存储file
        // 方法返回值为路径+文件名
        try {
            String path = easyActService.fileUpload(file);
            // 指向文件路径
            File f = new File(path);
            // 完成部署
            easyActService.saveNewDeploye(f, filename);
            return "新增成功";
        } catch (Exception e) {
            return "新增流程未成功，请检查上传参数是否正确";
        }

    }

    public String delDeployment(String deploymentId) {
        // 1：获取部署对象ID
        // 部署对象ID
        // 2：使用部署对象ID，删除流程定义
        try {
            easyActService.deleteProcessDefinitionByDeploymentId(deploymentId);
        } catch (Exception e) {

            return "删除失败，请确认该部署流程是否存在";
        }
        return "删除成功";
    }

    public String viewImage(String taskId) throws Exception {

        // 1：获取页面传递的部署对象ID和资源图片名称
        // 部署对象ID
        ProcessDefinition pd = easyActService.getProcessDefinitionByTaskId(taskId);
        // 1. 获取流程部署ID
        String deploymentId = pd.getDeploymentId();
//        String deploymentId = workFlow.getDeploymentId();
        // 资源图片名称
        String imageName = pd.getDiagramResourceName();
//        String imageName = workFlow.getImageName();
        // 2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = easyActService.findImageInputStream(deploymentId, imageName);
        // 将图片转换成字符串
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        String imgStr = UploadUtil.byte2hex(bytes);
//        // 3：从response对象获取输出流
//        OutputStream out = response.getOutputStream();
//        // 4：将输入流中的数据读取出来，写到输出流中
//        for (int b = -1; (b = in.read()) != -1; ) {
//            out.write(b);
//        }
//
//        // 将图写到页面上，用输出流写
//        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//        StringBuilder sb = new StringBuilder();
//        String line;
//        while ((line = reader.readLine()) != null) {
//            sb.append(line + "/r/n");
//        }
//        out.close();
        in.close();

        return imgStr;
    }

    public String viewImageByProId(String proId) throws Exception {

        // 1：获取页面传递的部署对象ID和资源图片名称
        // 部署对象ID
        ProcessDefinition pd = easyActService.getProcessDefinitionById(proId);
        // 资源图片名称
        // 1. 获取流程部署ID
        String deploymentId = pd.getDeploymentId();
        String imageName = pd.getDiagramResourceName();
//        String imageName = workFlow.getImageName();
        // 2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = easyActService.findImageInputStream(deploymentId, imageName);
        // 将图片转换成字符串
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        String imgStr = UploadUtil.byte2hex(bytes);
        in.close();
        return imgStr;
    }

    public String viewImageByDepId(String depId) throws Exception {
        // 获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        // 获取流程定义by部署对象ID
        ProcessDefinition pd = easyActService.getProcessDefinitionByDepId(depId);
        String imageName = pd.getDiagramResourceName();
        InputStream in = easyActService.findImageInputStream(depId, imageName);
        // 将图片转换成字符串
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        String imgStr = UploadUtil.byte2hex(bytes);
        in.close();
        return imgStr;
    }

    public String deleteProcessInstance(String taskId) throws Exception {
        return easyActService.deleteProcessInstance(taskId);
    }

    public String saveStartProcess(String className, String objId, String assignee) {
        try {
            Map<String, Object> variables = new HashMap();
            variables.put("assignee", assignee);
            easyActService.saveStartProcess(className, objId, variables);
            return "启动流程成功";
        } catch (Exception e) {
            return "启动流程失败";
        }
    }

    public String completeTask(String taskId, String outcome, String comment, String userMassage, String assignee, String assigneeList) {
        WorkFlow workFlow = new WorkFlow();
        List<String> list = new ArrayList<String>();
        Map<String, Object> variables = new HashMap();

        if (StringUtils.isNotBlank(assigneeList)) {
            String[] assignees = assigneeList.split(",");
            for (String ass : assignees) {
                ass=ass+".21";
                list.add(ass);
            }
            variables.put("assigneeList", list);
        }
        String eventId = "";
        String exeuId = "";
        String pdid = "";
        boolean flag = false;
        if (outcome.equals("协助维护")||outcome.equals("验证反馈")) {
            assignee = "20";
        }
        if (outcome.equals("维护完成")) {
            assignee = "2";
        }


        workFlow.setTaskId(taskId);
        workFlow.setOutcome(outcome);
        workFlow.setComment(comment);
        workFlow.setUserMassage(userMassage);
        assignee = assignee.toString();
        variables.put("assignee", assignee);
        easyActService.completeTask(workFlow, variables);//完成任务
        return "成功完成任务";
    }

    public Map<String, Object> findEventByTaskId(String taskId) {
        return easyActService.findEvent(taskId);
    }


    public List<TaskBean> findTaskList(String userId) {//userId为task表中Assignee的值
        return easyActService.findTaskList(userId);
    }

    public List<String> getTasksAndAssigneeNotnull() {
        return easyActService.getTasksAndAssigneeNotnull();
    }

    public List<String> getOrgs(String taskKey, String id, String objectName) {//userId为task表中Assignee的值
        return easyActService.getOrgs(taskKey, id, objectName);
    }

    public int updateVar(String assignee, String taskId) {//userId为task表中Assignee的值
        return easyActService.updateVar(assignee, taskId);
    }

    public List<String> findHisTaskList(String userId) {//userId为task表中Assignee的值
        return easyActService.findHisTaskList(userId);
    }

    public List<TaskBean> findGroupList(String roleId) {
        List<TaskBean> list = easyActService.findGroupList(roleId);
        return list;
    }

    public String claim(String taskId, String userId) {//任务ID,分配的办理人
        easyActService.claim(taskId, userId);
        return "success";
    }

    public String rollbackGroup(String taskId) {//任务ID,分配的办理人
        easyActService.rollbackGroup(taskId);
        return "success";
    }

    public String rollBackAct(String taskId) {
        return easyActService.rollBackAct(taskId);
    }

    public String rollBackToAssignAct(String taskId, String destTaskkey) {
        return easyActService.rollBackToAssignAct(taskId, destTaskkey);
    }

    public List<Comment> findCommentByObjecId(String className, String id) {
        List<Comment> list = easyActService.findCommentByObjecId(className, id);//查询历史意见
        return list;
    }

    public List<String> findOutComeListByTaskId(String taskId) {
        List<String> list = easyActService.findOutComeListByTaskId(taskId);//查询历史意见
        return list;
    }

    public String findTask(String objectId, String objectName, String assignee) {
        String taskId = easyActService.findTask(objectId, objectName, assignee);//查询历史意见
        return taskId;
    }

    public List<String> findAssigneeListByObjecId(String objectName, String id) {
        List<String> assignees = easyActService.findAssigneeListByObjecId(objectName, id);//查询历史意见
        return assignees;
    }

    public String findTaskIdByObjecId(String objectName, String id) {
        String taskId = easyActService.findTaskIdByObjecId(objectName, id);//查询历史意见
        return taskId;
    }

    public boolean findTaskIdOnlyOne(String objectName, String taskId) {
        boolean flag = easyActService.findTaskIdOnlyOne(objectName, taskId);
        return flag;
    }

    public String findTaskIdByObjecIdAndAssigneeIsNull(String objectName, String id, String roleids) {
        String taskId = easyActService.findTaskIdByObjecIdAndAssigneeIsNull(objectName, id, roleids);//查询历史意见
        return taskId;
    }

    public Map<String, Object> findCoordingByTask(String taskId) {
        return easyActService.findCoordingByTask(taskId);
    }

    public int getCount(String taskKey, String assignees) {
        return easyActService.getCount(taskKey, assignees);
    }

}